package com.jmlee.controller;

import com.jmlee.util.JSONUtil;
import com.jmlee.vo.AddressByRiderVo;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author： 郑锦涛
 * @data： 2021/3/12 19:52
 * @version：1.0
 * @描述： WebSocket   接收心跳 ，推送websocket方法
 */

@ServerEndpoint("/webSocket")
@Component
public class WebSocketServerEndpoint {

    /**
     * sessions     发送的sessions
     * addressByRiderVo     接收的数据，供RiderController中的sendOrderByWebSocket（）方法使用
     */
    public static Session sessions;
    public static AddressByRiderVo addressByRiderVo;


    /**
     * webSocket心跳
     *
     * @param session
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void handleMessage(Session session, String message) throws IOException {
        addressByRiderVo = JSONUtil.jsonToPojo(message,AddressByRiderVo.class);
        sessions = session;
        session.getBasicRemote().sendText("pong");

    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        sessions.getBasicRemote().sendText(message);
    }


}
